/*
 *             Copyright (C) 2024 Steve Jrong
 *
 * 	   GitHub Homepage: https://www.github.com/SteveJrong
 *      Gitee Homepage: https://gitee.com/stevejrong1024
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.stevejrong.waiter.rp.executor.query;

import java.util.List;
import java.util.UUID;

import org.springframework.stereotype.Component;

import com.alibaba.cola.dto.SingleResponse;
import com.stevejrong.waiter.common.component.BaseConstants;
import com.stevejrong.waiter.common.component.util.JsonUtil;
import com.stevejrong.waiter.mq.message.component.DomainEventPublisher;
import com.stevejrong.waiter.rp.assembler.MerchantUserPermissionAssembler;
import com.stevejrong.waiter.rp.dto.merchantuser.event.InitializedMerchantUserPermissionUrlAndCodeEvent;
import com.stevejrong.waiter.rp.gateway.IMerchantUserPermissionGateway;
import com.stevejrong.waiter.rp.model.aggregates.MerchantUserPermission;

import lombok.AllArgsConstructor;

/**
 * 查询执行器 - 初始化商家用户的后端权限信息到消息队列中
 *
 * @author Steve Jrong
 * @since 1.0
 */
@Component
@AllArgsConstructor
public class InitialBackendPermissionForMerchantUserCmdQryExe {
    private IMerchantUserPermissionGateway merchantUserPermissionGateway;

    private DomainEventPublisher authAppDomainEventPublisher;

    public SingleResponse execute(String originalTag) {
        // 简单逻辑，不依赖领域层，直接调用路由查询
        List<MerchantUserPermission> merchantUserPermissions = merchantUserPermissionGateway.getAllPermissions(); // 返回DO

        // 已查询到需要的数据，发布领域事件
        InitializedMerchantUserPermissionUrlAndCodeEvent event = new InitializedMerchantUserPermissionUrlAndCodeEvent();
        // 事件是向外发布的，而从领域层返上来的数据是DO，故需要使用组装器进行转换
        event.setData(MerchantUserPermissionAssembler.getDTOsFromDOs(merchantUserPermissions)); // 转DTO

        String topic = "Topic_Sync_Permission";
        // String tag = "RESPONSE" + BaseConstants.SymbolConstants.SYMBOL_UNDER_LINE.desc() + originalTag;
        String tag = BaseConstants.SymbolConstants.SYMBOL_ASTERISK.desc();
        String uniqueKey = UUID.randomUUID().toString();
        authAppDomainEventPublisher.sendAsync(topic, tag, uniqueKey, JsonUtil.objectToJsonString(event));

        return SingleResponse.buildSuccess();
    }
}